package ohc.login.mixin;

import net.minecraft.network.packet.c2s.play.ChatMessageC2SPacket;
import net.minecraft.network.packet.c2s.play.CommandExecutionC2SPacket;
import net.minecraft.network.packet.c2s.play.PlayerActionC2SPacket;
import net.minecraft.server.network.ServerPlayNetworkHandler;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import ohc.login.LoginManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

/**
 * 阻止未登录玩家的聊天和命令操作
 */
@Mixin(ServerPlayNetworkHandler.class)
public class PlayerActionMixin {
    
    @Shadow
    public ServerPlayerEntity player;
    
    /**
     * 阻止未登录玩家的操作
     */
    @Inject(method = "onPlayerAction", at = @At("HEAD"), cancellable = true)
    private void onPlayerAction(PlayerActionC2SPacket packet, CallbackInfo ci) {
        if (!LoginManager.INSTANCE.isLoggedIn(player.getUuid())) {
            PlayerActionC2SPacket.Action action = packet.getAction();
            // 阻止丢弃物品
            if (action == PlayerActionC2SPacket.Action.DROP_ITEM || 
                action == PlayerActionC2SPacket.Action.DROP_ALL_ITEMS) {
                // 同步背包
                player.playerScreenHandler.syncState();
                ci.cancel();
            }
        }
    }
    
    /**
     * 阻止未登录玩家发送聊天消息
     */
    @Inject(method = "onChatMessage", at = @At("HEAD"), cancellable = true)
    private void onChatMessage(ChatMessageC2SPacket packet, CallbackInfo ci) {
        if (!LoginManager.INSTANCE.isLoggedIn(player.getUuid())) {
            player.sendMessage(
                Text.literal("§c请先登录后再发送消息！").formatted(Formatting.RED)
            );
            ci.cancel();
        }
    }
    
    /**
     * 拦截命令执行
     */
    @Inject(method = "onCommandExecution", at = @At("HEAD"), cancellable = true)
    private void onCommandExecution(CommandExecutionC2SPacket packet, CallbackInfo ci) {
        if (!LoginManager.INSTANCE.isLoggedIn(player.getUuid())) {
            String command = packet.command();

            // 允许的命令白名单
            if (!command.startsWith("bind ") && 
                !command.startsWith("l ") && 
                !command.startsWith("login ") &&
                !command.startsWith("r ") &&
                !command.startsWith("dl ")) {
                player.sendMessage(
                    Text.literal("§c请先登录后再使用其他命令！").formatted(Formatting.RED)
                );
                ci.cancel();
            }
        }
    }
}
